//
//  Speaker.m
//  SHPE Conference Companion
//
//  Created by Richard Kirk on 3/25/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "Speaker.h"
#import "Conference.h"
#import "Session.h"


@implementation Speaker
@dynamic id;
@dynamic firstName;
@dynamic lastName;
@dynamic biography;
@dynamic website;
@dynamic linkedIn;
@dynamic email;
@dynamic organizationOrCompany;
@dynamic title;
@dynamic photoURL;
@dynamic photoData;
@dynamic conference;
@dynamic sessions;
@synthesize parent;

@synthesize xmlParser, xmlStringBuilder;

-(id)initWithParser:(NSXMLParser *)parser attributeDict:(NSDictionary *)attributes parent:(id)parentObject
{   
    
    [super initWithEntity:[NSEntityDescription entityForName:@"Speaker" inManagedObjectContext:[self managedObjectContext] ] insertIntoManagedObjectContext:[self managedObjectContext]];
    
    [parser setDelegate:self];
    [self setParent:parentObject];
    
        
    self.id = [NSNumber numberWithInt:[[attributes objectForKey:@"id"] intValue]];
    self.photoURL = [NSString stringWithString:[attributes objectForKey:@"xlink:photo"]];
    self.photoData = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.photoURL]];
    
    
    return self;

}

-(id)initWithSpeakerId:(int)speakerId
{
    
    [super initWithEntity:[NSEntityDescription entityForName:@"Speaker" inManagedObjectContext:[self managedObjectContext] ] insertIntoManagedObjectContext:[self managedObjectContext]];

    xmlParser = [NSXMLParser alloc];
    xmlParser.delegate = self;
    
    [xmlParser initWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://openshpe.staging.shpe.org/conference/v1/speaker/%d", speakerId]]];    
    
    if (xmlParser){
        [xmlParser parse];
    }
    
    
    return self;
}

-(NSString *)description
{
    
    
    return [NSString stringWithFormat:@"\nSpeakerid : %@\nFirst Name : %@\nLast Name : %@\nTitle : %@\norganizationOrCompany : %@\nEmail : %@\nlinkedIn : %@\nWebsite : %@\nPhotoURL : %@\nBiography : %@\n", self.id, self.firstName, self.lastName, self.title, self.organizationOrCompany, self.email, self.linkedIn, self.website, self.photoURL, self.biography];
    
}




- (void)addSessionsObject:(Session *)value {    
    NSSet *changedObjects = [[NSSet alloc] initWithObjects:&value count:1];
    [self willChangeValueForKey:@"sessions" withSetMutation:NSKeyValueUnionSetMutation usingObjects:changedObjects];
    [[self primitiveValueForKey:@"sessions"] addObject:value];
    [self didChangeValueForKey:@"sessions" withSetMutation:NSKeyValueUnionSetMutation usingObjects:changedObjects];
    [changedObjects release];
}

- (void)removeSessionsObject:(Session *)value {
    NSSet *changedObjects = [[NSSet alloc] initWithObjects:&value count:1];
    [self willChangeValueForKey:@"sessions" withSetMutation:NSKeyValueMinusSetMutation usingObjects:changedObjects];
    [[self primitiveValueForKey:@"sessions"] removeObject:value];
    [self didChangeValueForKey:@"sessions" withSetMutation:NSKeyValueMinusSetMutation usingObjects:changedObjects];
    [changedObjects release];
}

- (void)addSessions:(NSSet *)value {    
    [self willChangeValueForKey:@"sessions" withSetMutation:NSKeyValueUnionSetMutation usingObjects:value];
    [[self primitiveValueForKey:@"sessions"] unionSet:value];
    [self didChangeValueForKey:@"sessions" withSetMutation:NSKeyValueUnionSetMutation usingObjects:value];
}

- (void)removeSessions:(NSSet *)value {
    [self willChangeValueForKey:@"sessions" withSetMutation:NSKeyValueMinusSetMutation usingObjects:value];
    [[self primitiveValueForKey:@"sessions"] minusSet:value];
    [self didChangeValueForKey:@"sessions" withSetMutation:NSKeyValueMinusSetMutation usingObjects:value];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict 
{
    
    if ( ( [elementName isEqualToString:@"conference-speaker"] )) {
        self.id = [NSNumber numberWithInt:[[attributeDict objectForKey:@"id"] intValue]];
        self.photoURL = [NSString stringWithString:[attributeDict objectForKey:@"xlink:photo"]];
        self.photoData = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.photoURL]];
        return;
    }
    
    if ( ( [elementName isEqualToString:@"name"] )) {
        
        self.firstName = [NSString stringWithString:[attributeDict objectForKey:@"first"]];
        self.lastName  = [NSString stringWithString:[attributeDict objectForKey:@"last"]];
        
        return;
    }
    
        //This doesnt do anything now, but IF we want to list all of the conferences
        //that a speaker has attended, we would implement this.
    /*
     if ( ( [elementName isEqualToString:@"conference"] )) {
     self.conferenceId = [NSNumber numberWithInt:[[attributeDict objectForKey:@"id"] intValue]];
     return;
     }
     
     */
    
}



- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string 
{   string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    string = [string stringByReplacingOccurrencesOfString:@"&amp;" withString:@" & "];
    string = [string stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
    string = [string stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
    if (!xmlStringBuilder) {
        xmlStringBuilder = [[NSMutableString alloc] initWithCapacity:100];
    }
    
    [xmlStringBuilder appendString:string];
    
    
}

-(void)parser:(NSXMLParser *)parser foundIgnorableWhitespace:(NSString *)whitespaceString
{    
    
        //Didnt need this 
    /**
     
     NSLog(@"\nfound ignoreable whitespace: whitespace string: \"%@\"\n", whitespaceString);
     if (!xmlStringBuilder) {
     xmlStringBuilder = [[NSMutableString alloc] initWithCapacity:100];
     
     }
     //   if (whitespaceString != @"\n")
     // [xmlStringBuilder appendString:whitespaceString];
     
     */
    
}


- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    
    
        // ignore root and empty elements
    if ( [elementName isEqualToString:@"conference-speaker"] ) {
        [parser setDelegate:parent];
        xmlStringBuilder = nil;
        return;
    }
    
    else if( [elementName isEqualToString:@"title"] ) {
        
        self.title =[NSString stringWithString:xmlStringBuilder];
        
    }
    
    else if( [elementName isEqualToString:@"organizationOrCompany"] ) {
        self.organizationOrCompany = [NSString stringWithString:xmlStringBuilder];
        
    }
    
    else if( [elementName isEqualToString:@"email"] ) {
        self.email = [NSString stringWithString:xmlStringBuilder];
        
    }
    
    else if( [elementName isEqualToString:@"linkedIn"] ) {
        self.linkedIn = [NSString stringWithString:xmlStringBuilder];
        
    }
    
    else if( [elementName isEqualToString:@"website"] ) {
        self.website = [NSString stringWithString:xmlStringBuilder];
        
    }
    
    else if( [elementName isEqualToString:@"biography"] ) {
        self.biography = [NSString stringWithString:xmlStringBuilder];
        
    }
    
    
    
    xmlStringBuilder = nil;
    
    
    
}



-(void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
    
    NSLog(@"XML ERROR :\n%@\n",[parseError description]);
    
    UIAlertView *parserAlert = [[UIAlertView alloc]init];
    
    
    [parserAlert setTitle:@"Parsing Error!"];
    
    [parserAlert setMessage:[NSString stringWithFormat:@"Error %i, Description: %@, Line: %i, Column: %i", 
                             [parseError code], 
                             [parseError localizedDescription], 
                             [parser lineNumber], 
                             [parser columnNumber]]];
    
    [parserAlert addButtonWithTitle:@"OK"];
    [parserAlert show];
    [parserAlert release];
    
    
    
}



@end
